<template>
  <div>
    <Navigation></Navigation>
    <div class="home">
      <div class="left">
        <div class="chat">
          聊天
          <el-tooltip
            class="item"
            effect="dark"
            content="新建分组"
            placement="top"
          >
            <el-button
              style="margin-left: 70%"
              type="primary"
              size="mini"
              icon="el-icon-present"
            ></el-button>
          </el-tooltip>
        </div>
        <div class="search">
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="keywords"
            clearable
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </div>
        <div
          class="user"
          :class="item.chatType === 2 ? 'user_bg' : 'user'"
          @click="initUserChat(item)"
          v-for="item in chatList"
          :key="item.id"
        >
          <div class="avatar">
            <el-avatar :src="item.avatar"></el-avatar>
          </div>
          <div class="username">
            <div style="font-size: 15px">
              {{ item.username }}
              <span
                style="
                  position: absolute;
                  right: 15px;
                  font-size: 20px;
                  top: -5px;
                "
              >
                <el-popover placement="bottom" width="150" trigger="hover">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="置顶"
                    placement="top"
                  >
                    <el-button
                      @click="topChat(item)"
                      type="success"
                      icon="el-icon-top"
                      circle
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <el-button
                      @click="deleteChat(item)"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="取消置顶"
                    placement="top"
                  >
                    <el-button
                      @click="cancelTopChat(item)"
                      type="danger"
                      icon="el-icon-close"
                      circle
                    ></el-button>
                  </el-tooltip>
                  <i
                    v-if="item.count === 0"
                    slot="reference"
                    class="el-icon-more-outline"
                  ></i>
                </el-popover>
              </span>
              <el-badge
                v-if="item.count > 0"
                style="position: absolute; right: 15px; font-size: 20px"
                :value="item.count"
                :max="99"
                class="item"
              ></el-badge>
              <i
                style="
                  position: absolute;
                  right: 15px;
                  font-size: 20px;
                  font-size: 12px;
                  color: #909399;
                  top: 30px;
                "
              >
                {{ item.chatDate | dateFilter }}
              </i>
            </div>
            <div style="font-size: 13px; color: #909399; margin-top: 5px">
              {{ item.latestMessage }}
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="header">
          <div class="right-avatar">
            <el-avatar :src="chatUser.avatar"></el-avatar>
          </div>
          <div class="right-username">
            <div style="font-size: 15px">{{ chatUser.username }}</div>
            <div style="font-size: 12px; color: #909399; margin-top: 2px">
              正在输入中
            </div>
          </div>
          <div class="right-icon">
            <el-button
              size="small "
              type="primary"
              icon="el-icon-phone"
            ></el-button>
            <el-button
              size="small "
              type="success"
              icon="el-icon-phone-outline"
            ></el-button>
            <el-popover placement="bottom" width="150" trigger="hover">
              <el-tooltip
                class="item"
                effect="dark"
                content="置顶"
                placement="top"
              >
                <el-button
                  @click="topChat(chatUser)"
                  type="success"
                  icon="el-icon-top"
                  circle
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  @click="deleteChat(chatUser)"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="取消置顶"
                placement="top"
              >
                <el-button
                  @click="cancelTopChat(chatUser)"
                  type="danger"
                  icon="el-icon-close"
                  circle
                ></el-button>
              </el-tooltip>
              <el-button
                style="margin-left: 10px"
                slot="reference"
                size="small "
                type="info"
                icon="el-icon-more"
              ></el-button>
            </el-popover>
          </div>
        </div>
        <div id="content" class="content">
          <div v-for="item in msgList" :key="item.id">
            <div class="message-left" v-show="item.cid === chatUser.cid">
              <div class="message-avatar">
                <el-avatar :src="item.avatar"></el-avatar>
              </div>
              <div class="message-username">
                <div style="font-size: 12px">{{ item.username }}</div>
                <div class="msg-content">{{ item.content }}</div>
                <div
                  style="
                    font-size: 12px;
                    color: #909399;
                    margin: 5px;
                    font-style: italic;
                  "
                >
                  {{ item.date }}
                </div>
              </div>
            </div>
            <div class="message-right" v-show="item.cid != chatUser.cid">
              <div class="message-username">
                <div style="font-size: 12px; text-align: right">
                  {{ item.username }}
                </div>
                <div style="height: 100%">
                  <div
                    class="msg-content"
                    style="background-color: #95ec69; float: right"
                  >
                    {{ item.content }}
                  </div>
                </div>
                <div
                  style="
                    font-size: 12px;
                    color: #909399;
                    margin: 5px;
                    margin-top: -12px;
                    font-style: italic;
                    text-align: right;
                  "
                >
                  {{ item.date }}
                </div>
              </div>
              <div class="message-avatar" style="text-align: right">
                <el-avatar :src="item.avatar"></el-avatar>
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <input
            class="input"
            placeholder="按 Enter 发送"
            v-model="content"
            :rows="1"
            @keyup="onKeyup"
          />
            <el-popover
                    style="margin-right: 10px;"
                    placement="bottom"
                    width="430"
                    trigger="click"
                    >
                <li class="emojiList" v-for="(item, index) in emojis" :key="index" @click="selectEmoji(item)">
                    {{item.text}}
                </li>
                <el-button
                        slot="reference"
                        class="icon"
                        type="warning"
                        icon="el-icon-picture-outline-round"
                        circle
                ></el-button>
            </el-popover>
            <el-button
                    class="icon"
                    type="info"
                    icon="el-icon-paperclip icon"
                    circle
            ></el-button>
          <el-button
            class="icon"
            type="primary"
            icon="el-icon-microphone icon"
            circle
          ></el-button>
          <el-button
            @click="sendMsg"
            class="icon"
            type="success"
            icon="el-icon-s-promotion icon"
            circle
          ></el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Navigation from "../components/Navigation.vue";
import ReconnectingWebSocket from "reconnecting-websocket";
import { getChatList } from "@/api/friend";
import { getMsgList, sendMessage, updateMsgType } from "@/api/message";
import moment from "moment";
import dateFilter from "@/filter";
import { isNotEmpty } from "@/utils/common";
import { emojis } from "@/assets/emojis";
export default {
  name: "Home",
  components: {
    Navigation,
  },

  data() {
    return {
      keywords: "",
      content: "",
      chatList: [],
      chatUser: {},
      msgList: [],
      messageUrl: "ws://localhost:8090/ws/message/",
      chatUrl: "ws://localhost:8090/ws/chat/",
      messageSocket: "",
      chatSocket: "",
      cid: "",
      emojis: [],
    };
  },
  created() {
    let cid = this.$route.params.cid;
    if (isNotEmpty(cid)) {
      this.cid = cid;
    }
    this.initChatList();
    this.websocketMessageInit();
    this.websocketChatInit();
    this.emojis = emojis.map((emoji) => ({ text: emoji }));
  },
  methods: {
    selectEmoji(e) {
      this.content += e.text;
    },
    //websocketChatInit初始化
    websocketChatInit() {
      // 建立websocket 连接
      let cid = this.$cookies.get("cid");
      if (isNotEmpty(cid)) {
        let url = this.chatUrl + cid;
        this.chatSocket = new ReconnectingWebSocket(url);
        this.chatSocket.addEventListener("open", () => {
          if (!this.chatSocket) return;
          if (this.chatSocket.readyState === 1) {
            console.log("建立成功，发送消息");
          }
        });
      }

      //收信
      this.chatSocket.addEventListener("message", (e) => {
        //消息进入后的处理逻辑
        let newChat = JSON.parse(e.data);
        newChat.chatDate = moment(
          new Date(newChat.chatDate).getTime() - 8 * 60 * 60 * 1000
        ).format("MM-DD HH:mm");
        if (this.chatList !== [] && this.chatList.length > 0) {
          let topChatList = this.chatList.filter((e) => e.chatType === 2);
          this.chatList.splice(topChatList.length, 0, newChat);
        }
      });

      // 错误时进行的处理
      this.chatSocket.addEventListener("error", (e) => {
        console.error(e.message);
      });

      // 关闭时进行的操作
      this.chatSocket.addEventListener("close", () => {
        this.chatSocket.close();
        console.log("chatSocket已关闭");
      });
    },
    //websocketMessageInit初始化
    websocketMessageInit() {
      // 建立websocket 连接
      let cid = this.$cookies.get("cid");
      if (isNotEmpty(cid)) {
        let url = this.messageUrl + cid;
        this.messageSocket = new ReconnectingWebSocket(url);
        this.messageSocket.addEventListener("open", () => {
          if (!this.messageSocket) return;
          if (this.messageSocket.readyState === 1) {
            console.log("建立成功，发送消息");
          }
        });
      }

      //收信
      this.messageSocket.addEventListener("message", (e) => {
        //消息进入后的处理逻辑
        let newMessage = JSON.parse(e.data);
        newMessage.date = moment(
          new Date(newMessage.date).getTime() - 8 * 60 * 60 * 1000
        ).format("HH:mm");
        let cid = this.$cookies.get("cid");
        if (newMessage.cid === cid) {
          //自己在发送消息
          this.msgList.push(newMessage);
        } else {
          //好友发送消息
          if (this.chatUser.cid === newMessage.cid) {
            //当前会话
            this.msgList.push(newMessage);
          } else {
            //不是当前会话，通知新消息
            if (this.chatList !== [] && this.chatList.length > 0) {
              this.chatList.forEach((chat) => {
                if (chat.cid === newMessage.cid) {
                  chat.count++;
                  chat.latestMessage = newMessage.content;
                }
              });
            }
          }
        }
      });

      // 错误时进行的处理
      this.messageSocket.addEventListener("error", (e) => {
        console.error(e.message);
      });

      // 关闭时进行的操作
      this.messageSocket.addEventListener("close", () => {
        this.messageSocket.close();
        console.log("messageSocket已关闭");
      });
    },
    //初始话聊天列表
    initChatList() {
      let data = {
        cid: this.$cookies.get("cid"),
      };
      getChatList(data)
        .then((res) => {
          this.chatList = res.data;
          if (res.data.length > 0) {
            if (isNotEmpty(this.cid)) {
              this.chatUser = res.data.filter((e) => e.cid === this.cid)[0];
              this.initChatMsgList(this.chatUser);
            } else {
              this.chatUser = res.data[0];
              this.initChatMsgList(res.data[0]);
            }
          } else {
            this.msgList = [];
            this.chatUser = {};
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //初始话聊天消息内容
    initUserChat(item) {
      this.chatUser = item;
      this.initChatMsgList(item);
      if (this.chatList !== [] && this.chatList.length > 0) {
        this.chatList.forEach((chat) => {
          if (chat.cid === item.cid) {
            chat.count = 0;
          }
        });
      }
    },
    //初始化消息
    initChatMsgList(item) {
      let message = {
        toUserId: item.cid,
        formUserId: this.$cookies.get("cid"),
      };
      getMsgList(message)
        .then((res) => {
          this.msgList = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    cancelTopChat(item) {
      //取消置顶
      let message = {
        toUserId: item.cid,
        formUserId: this.$cookies.get("cid"),
        chatType: 1,
      };
      updateMsgType(message)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("取消成功");
            this.initChatList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    topChat(item) {
      //置顶消息
      let message = {
        toUserId: item.cid,
        formUserId: this.$cookies.get("cid"),
        chatType: 2,
      };
      updateMsgType(message)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("置顶成功");
            this.initChatList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    deleteChat(item) {
      //删除聊天
      let message = {
        toUserId: item.cid,
        formUserId: this.$cookies.get("cid"),
        chatType: 0,
      };
      if (isNotEmpty(this.cid) && item.cid === this.cid) {
        this.cid = "";
      }
      updateMsgType(message)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.initChatList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //发送消息
    onKeyup(e) {
      if (e.keyCode === 13 && this.content.length) {
        let message = {
          content: this.content,
          toUserId: this.chatUser.cid,
          formUserId: this.$cookies.get("cid"),
        };
        sendMessage(message)
          .then((res) => {
            if (res.code === 200) {
              this.content = "";
              this.$message.success("发送成功");
            } else {
              this.$message.error("发送失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    //发送消息
    sendMsg() {
      if (this.content.length) {
        let message = {
          content: this.content,
          toUserId: this.chatUser.cid,
          formUserId: this.$cookies.get("cid"),
        };
        sendMessage(message)
          .then((res) => {
            if (res.code === 200) {
              this.content = "";
              this.$message.success("发送成功");
            } else {
              this.$message.error("发送失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
  watch: {
    //用户名搜索
    keywords(value) {
      if (!isNotEmpty(value)) {
        this.initChatList();
      } else {
        this.chatList = this.chatList.filter((e) => e.username.includes(value));
      }
    },
    //监听消息，发生变化滑到最底部（异步去操作）
    msgList(value) {
      if (isNotEmpty(value)) {
        this.$nextTick(() => {
          let element = document.getElementById("content");
          element.scrollTop = element.scrollHeight;
        });
      }
    },
  },
};
</script>

<style scoped>
.emojiList {
  display: inline-flex;
  font-size: 24px;
  margin: 5px;
}
.emojiList:hover {
  cursor: pointer;
}
.home {
  margin: 12px;
  margin-left: 114px;
  display: flex;
  height: calc(100vh - 1.9rem);
}
.left {
  flex: 1;
  background-color: #fff;
  border-radius: 10px;
  margin-top: 5px;
}
.chat {
  margin: 20px;
  font-weight: bolder;
  font-size: 16px;
}
.right {
  flex: 4.5;
  margin-top: 5px;
  margin-left: 10px;
  background-color: #ebebeb;
  border-radius: 10px;
}
.search {
  margin: 10px;
}
.user {
  display: flex;
  padding-bottom: 10px;
  padding-top: 10px;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
}

.user_bg {
  background-color: #ebeef5;
}
.user:hover {
  background-color: #ebeef5;
}
.user .username span {
  opacity: 0;
}
.user:hover .username span {
  opacity: 1;
}
.avatar {
  flex: 1;
  text-align: center;
}
.username {
  flex: 4;
  position: relative;
}
.header {
  display: flex;
  margin-top: 10px;
  padding-bottom: 10px;
  border-bottom: 2px solid #dcdfe6;
}
.right-avatar {
  flex: 1;
  text-align: center;
}
.right-username {
  flex: 18;
}
.right-icon {
  flex: 3;
  text-align: center;
  margin: 5px;
}
.content {
  width: 100%;
  height: 773px;
  overflow: hidden;
  overflow-y: visible;
  border-bottom: 2px solid #dcdfe6;
}
.message-left {
  display: flex;
  margin: 10px;
}
.message-avatar {
  flex: 1;
}
.message-username {
  flex: 28;
}
.message-right {
  display: flex;
  margin: 10px;
  margin-top: 35px;
}
.msg-content {
  background-color: #fff;
  font-size: 16px;
  line-height: 25px;
  border-radius: 5px;
  margin-top: 5px;
  padding: 8px 10px 8px 10px;
  max-width: 800px;
  min-height: 22px;
  width: fit-content;
}
.footer {
  margin-top: 5px;
  background-color: #fff;
  height: 55px;
  border-radius: 10px;
}
.input {
  padding: 15px;
  /* height: 100%; */
  font-size: 16px;
  width: 1220px;
  border: none;
  outline: none;
  font-family: "Micrsofot Yahei";
  resize: none;
  border-radius: 5px;
}
</style>
